<?php
require_once "DatabaseManager.php";
require_once "UsersManager.php";


class RoomsManager extends DatabaseManager {
	
	private function getRoomsByName($keyWord, $take, $skip) {
		// To lower
		$keyWord = strtolower($keyWord);
		// Querystring
		$queryString = "SELECT r.id as room_id, r.name as room_name, b.name as building_name FROM rooms as r INNER JOIN buildings as b ON  r.building_id = b.id WHERE r.name like '$keyWord%' ORDER BY r.name LIMIT $take OFFSET $skip";
        $totalQueryString = "SELECT count(*) as total FROM rooms WHERE name like '$keyWord%'";
		$queryResults = mysql_query($queryString, $this->connection);
		$numberOfRows = mysql_num_rows($queryResults);
		if ($numberOfRows > 0) {
			// Rooms were found
			
			 $jsonRooms = array();
			 while ($row = mysql_fetch_array($queryResults)) {
				 $roomJSON = array();
				 
				// Room Id
				$roomJSON[JSON_Tags::ROOM_ID] = $row['room_id'];
				// Room Name
				$roomJSON[JSON_Tags::ROOM_NAME] = $row['room_name'];
				// Building Name
				$roomJSON[JSON_Tags::BUILDING_NAME] = $row['building_name'];
				// Self_URL
				$roomJSON[JSON_Tags::SELF_URL] = PROTOCOL.$_SERVER['SERVER_NAME'].EntryPoints::API.EntryPoints::ROOMS.'/'.$row['room_id'];
				
				array_push($jsonRooms, $roomJSON);
			 }
            // Get total number of items
            $queryResults = mysql_query($totalQueryString, $this->connection);
            $row = mysql_fetch_array($queryResults);
            
            $jsonResults = array();
            $jsonResults[JSON_Tags::TOTAL_ITEMS] = $row['total'];
            $jsonResults[JSON_Tags::ITEMS] = $jsonRooms;
			 // Send the response
			 $this->response($this->toJSON($jsonResults),StatusCodes::STATUS_CODE_SUCCESS);
		 }
		 else {
			// No results
			$jsonResults[MESSAGE] = Strings::NO_ROOMS_RESULTS_MESSAGE;
			$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_NOT_FOUND); 
		 }
	}
	
	private function getRoomDetailsById($id) {		
		// Querystring
		$queryString = "SELECT r.id as room_id, r.name as room_name, r.has_projector as room_has_projector, r.number_of_places as room_no_of_places, b.id as building_id, b.name as building_name, b.street as building_street, b.zip_code as building_zipcode, b.city as building_city, b.latitude as building_latitude, b.longitude as building_longitude FROM rooms as r INNER JOIN buildings as b ON  r.building_id = b.id WHERE r.id = $id";
		$queryResults = mysql_query($queryString, $this->connection);
		$numberOfRows = mysql_num_rows($queryResults);
		if ($numberOfRows > 0) {
			// Room was found were found
			$row = mysql_fetch_array($queryResults);
			//  Room
			$roomJSON = array();
			// Room Id
			$roomJSON[JSON_Tags::ROOM_ID] = $row['room_id'];
			// Room Name
			$roomJSON[JSON_Tags::ROOM_NAME] = $row['room_name'];
			// Room Has Projector
			$roomJSON[JSON_Tags::ROOM_HAS_PROJECTOR] = $row['room_has_projector'];
			// Room Number Of Places
			$roomJSON[JSON_Tags::ROOM_NUMBER_OF_PLACES] = $row['room_no_of_places'];
			// Self_URL
			$roomJSON[JSON_Tags::SELF_URL] = PROTOCOL.$_SERVER['SERVER_NAME'].EntryPoints::API.EntryPoints::ROOMS.'/'.$row['room_id'];
			// Bookings_URL
			$roomJSON[JSON_Tags::ROOM_BOOKINGS_URL] = PROTOCOL.$_SERVER['SERVER_NAME'].EntryPoints::API.EntryPoints::BOOKINGS.EntryPoints::ROOMS.'/'.$row['room_id'].'?date={date}';
			// Building
			$buildingJSON = array();
			// Building Id
			$buildingJSON[JSON_Tags::BUILDING_ID] = $row['building_id'];
			// Building Name
			$buildingJSON[JSON_Tags::BUILDING_NAME] = $row['building_name'];
			// Building Street
			$buildingJSON[JSON_Tags::BUILDING_STREET] = $row['building_street'];
			// Building Zipcode
			$buildingJSON[JSON_Tags::BUILDING_ZIPCODE] = $row['building_zipcode'];
			// Building City
			$buildingJSON[JSON_Tags::BUILDING_CITY] = $row['building_city'];
			// Building Latitude
			$buildingJSON[JSON_Tags::BUILDING_LATITUDE] = $row['building_latitude'];
			// Building Longitude
			$buildingJSON[JSON_Tags::BUILDING_LONGITUDE] = $row['building_longitude'];
				
			$roomJSON[JSON_Tags::BUILDING] = $buildingJSON;
				
	
			// Send the response
			$this->response($this->toJSON($roomJSON),StatusCodes::STATUS_CODE_SUCCESS);
		} else {
			// No results
			$jsonResults[MESSAGE] = Strings::INVALID_ROOM_ID;
			$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_NOT_FOUND); 
		}
	}
	
	private function getRoomsAvailableForFaculty($facultyId) {
	   $queryString = "SELECT r.id as room_id, r.name as room_name, b.name as building_name FROM rooms as r INNER JOIN buildings as b ON  r.building_id = b.id INNER JOIN rooms_faculties AS rf ON r.id = rf.room_id WHERE rf.faculty_id = $facultyId";
	   $queryResults = mysql_query($queryString, $this->connection);
	   $numberOfRows = mysql_num_rows($queryResults); 
	   if ($numberOfRows > 0) {
		   	// Rooms were found
			 $jsonResults = array();
             $jsonRooms = array();
			 while ($row = mysql_fetch_array($queryResults)) {
				 $roomJSON = array();
				 
				// Room Id
				$roomJSON[JSON_Tags::ROOM_ID] = $row['room_id'];
				// Room Name
				$roomJSON[JSON_Tags::ROOM_NAME] = $row['room_name'];
				// Building Name
				$roomJSON[JSON_Tags::BUILDING_NAME] = $row['building_name'];
				// Self_URL
				$roomJSON[JSON_Tags::SELF_URL] = PROTOCOL.$_SERVER['SERVER_NAME'].EntryPoints::API.EntryPoints::ROOMS.'/'.$row['room_id'];
				// Bookings_URL
				$roomJSON[JSON_Tags::ROOM_BOOKINGS_URL] = PROTOCOL.$_SERVER['SERVER_NAME'].EntryPoints::API.EntryPoints::BOOKINGS.EntryPoints::ROOMS.'/'.$row['room_id']."/?date={date}";
				array_push($jsonRooms, $roomJSON);
			 }
             $jsonResults[JSON_Tags::ITEMS] = $jsonRooms;
			 // Send the response
			 $this->response($this->toJSON($jsonResults),StatusCodes::STATUS_CODE_SUCCESS);
		 }
		 else {
			// No results
			$jsonResults[MESSAGE] = Strings::NO_ROOMS_RESULTS_MESSAGE;
			$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_NOT_FOUND); 
		 }
	}
	
	public function processApi() {
		// Check authorization token
		$userManager = new UsersManager();
		$userInfo = $userManager->getUserInfoForAuthorization();
		
		$METHOD = $this->get_request_method();
		if ($METHOD == "GET") {
			if (isset($_GET['keyword']) && isset($_GET['take']) && isset($_GET['skip'])) {
				// Get rooms by name
				$keyword = addslashes($_GET['keyword']);
				$take = $_GET['take'];
				$skip = $_GET['skip'];
				if (!is_numeric($take)) {
					// Take should be numeric
					$jsonResults[MESSAGE] = Strings::INVALID_TAKE;
					$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_NOT_FOUND); 
				}
				if (!is_numeric($skip)) {
					// Skip should be numeric
					$jsonResults[MESSAGE] = Strings::INVALID_SKIP;
					$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_NOT_FOUND); 
				}
				$this->getRoomsByName($keyword, $take, $skip);
				
			} else if (isset($_GET['roomId'])) {
				// Get room details	
				$roomId = addslashes($_GET['roomId']);
				$this->getRoomDetailsById($roomId);
			} else if (isset($_GET['facultyId'])) {
				// Get rooms for faculty	
				$facultyId = addslashes($_GET['facultyId']);
				$this->getRoomsAvailableForFaculty($facultyId);
			} else {
				// Bad request
				$jsonResults[MESSAGE] = Strings::BAD_REQUEST;
				$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST);
			}
		} 
		else {
			// Not supported method	
			$jsonResults[MESSAGE] = Strings::HTTP_METHOD_NOT_SUPPORTED;
			$this->response($this->toJSON($jsonResults), StatusCodes::STATUS_CODE_BAD_REQUEST);
		}
		return;
	}
}
?>